import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../standard/app_colors.dart';
import 'article_post_logic.dart';

class ArticlePostPage extends GetView<ArticlePostLogic> {
  const ArticlePostPage({this.landmarkId, super.key});

  final String? landmarkId;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ArticlePostLogic>(
        init: ArticlePostLogic(landmarkId),
        builder: (logic) {
          return BaseScaffold(
            titleStr: ' ',
            scaffoldBackgroundColor: Colors.white,
            actions: [
              CommonRootAction(
                onTap: controller.publish,
                child: ButtonWidget.text(
                  'Post',
                  fontSize: 12,
                  textColor: Colors.white,
                  width: 50,
                  height: 28,
                  alignment: Alignment.center,
                  gradient: AppColors.primaryGradient,
                  borderRadius: 28,
                  hasInkWell: false,
                ),
              ),
            ],
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildPics(),
                  _buildItem(title: 'Riding kilometers：', controller: controller.metersController).paddingTop(24.w),
                  CommonDivider(color: '#CCCCCC'.toColor),
                  _buildItem(title: 'Riding time：', controller: controller.timeController).paddingTop(24.w),
                  CommonDivider(color: '#CCCCCC'.toColor),
                  _buildItem(title: 'Enter your title：', controller: controller.titleController).paddingTop(24.w),
                  CommonDivider(color: '#CCCCCC'.toColor),
                  _buildIdeaInput().paddingTop(30.w),
                ],
              ),
            ).paddingHorizontal(20.w),
          );
        });
  }

  Widget _buildPics() {
    return GridView.builder(
        padding: EdgeInsets.only(top: 12.w),
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: min(controller.maxShow, controller.images.length + 1),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 12.w,
          crossAxisSpacing: 12.w,
          childAspectRatio: 0.835,
        ),
        itemBuilder: (BuildContext context, int index) {
          return index == controller.images.length ? _buildAdd() : _buildPic(controller.images[index], index);
        });
  }

  Widget _buildPic(PostArticleImageBean bean, int index) {
    bool uploadFinish = (bean.uploadEnd != null && bean.uploadEnd!);
    return Stack(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(12.w),
          child: FractionallySizedBox(
            heightFactor: 1,
            widthFactor: 1,
            child: ButtonWidget(
              onTap: () {},
              hasInkWell: false,
              child: AssetEntityImage(
                bean.assetEntity!,
                isOriginal: false,
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),
        if (uploadFinish)
          Positioned(
            top: 0,
            right: 0,
            child: ButtonWidget.icon(
              IconWidget.image(Assets.pngPostDelete, size: 24.w),
              onTap: () => controller.deleteImage(index),
            ),
          ),
        if (!uploadFinish)
          ClipRRect(
            borderRadius: BorderRadius.circular(12.w),
            child: Container(
              color: Colors.black.withOpacity(0.5),
              alignment: Alignment.center,
              child: SizedBox.fromSize(
                size: Size(24.w, 24.w),
                child: CircularProgressIndicator(
                  value: bean.progress,
                  color: AppColors.primary,
                  backgroundColor: Colors.white.withOpacity(0.3),
                  strokeWidth: 2.w,
                ),
              ),
            ),
          ),
        if (uploadFinish && bean.progress == -1)
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const TextWidget.oneLine(text: 'upload failed', fontSize: 14, color: Colors.red),
                Padding(padding: EdgeInsets.only(top: 10.w)),
                ButtonWidget(
                  onTap: () => controller.retry(index),
                  hasInkWell: false,
                  child: const TextWidget.oneLine(text: 'retry', fontSize: 14, color: AppColors.primary),
                ),
              ],
            ),
          )
      ],
    );
  }

  Widget _buildAdd() {
    return ButtonWidget.icon(
      IconWidget.image(Assets.pngPostAdd, size: 24.w),
      onTap: controller.chooseImage,
      backgroundColor: '#F6F8FA'.toColor,
      borderRadius: 12.w,
      alignment: Alignment.center,
      hasInkWell: false,
    );
  }

  Widget _buildInput({required TextEditingController controller, String? hintText}) {
    return TextField(
      decoration: InputDecoration(
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12.w),
          borderSide: const BorderSide(style: BorderStyle.none, width: 0),
        ),
        hintText: hintText,
        hintStyle: TextStyle(fontSize: 14, color: Colors.black.withOpacity(0.5)),
        fillColor: '#F6F8FA'.toColor,
        filled: true,
      ),
      cursorColor: AppColors.primary,
      controller: controller,
      style: const TextStyle(fontSize: 14),
      maxLines: 1,
    );
  }

  Widget _buildItem({required String title, required TextEditingController controller}) => Row(
        children: [
          TextWidget.oneLine(
            text: title,
            fontSize: 17,
            color: Colors.black.withOpacity(0.5),
            fontWeight: FontWeight.bold,
          ),
          TextField(
            decoration: const InputDecoration(border: InputBorder.none, hintText: ''),
            cursorColor: AppColors.primary,
            controller: controller,
            style: const TextStyle(fontSize: 17),
            maxLines: 1,
          ).expanded(),
        ],
      );

  Widget _buildIdeaInput() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(bg: '#F6F8FA'.toColor, radius: 12.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisSize: MainAxisSize.min,
        children: [
          TextField(
            decoration: InputDecoration(
              contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.w),
              border: InputBorder.none,
              hintText: 'Start creating your ideas.....',
              hintStyle: TextStyle(fontSize: 12, color: Colors.black.withOpacity(0.5)),
            ),
            cursorColor: AppColors.primary,
            controller: controller.ideaController,
            style: const TextStyle(fontSize: 12),
            maxLines: 10,
            inputFormatters: [LengthLimitingTextInputFormatter(controller.ideaMaxLength)],
          ),
          TextWidget.oneLine(
            text: '${controller.ideaController.text.length}/${controller.ideaMaxLength}',
            fontSize: 10,
            color: '#868686'.toColor,
          ).padding(bottom: 12.w, right: 12.w),
        ],
      ),
    );
  }
}
